import { CrudOptions, AddReq, DelReq, EditReq, dict, CrudExpose, UserPageQuery, CreateCrudOptionsRet } from '@fast-crud/fast-crud';
import * as api from './api';
import { auth } from "/@/utils/authFunction";
import { computed, ref } from 'vue';
import dayjs from 'dayjs';

interface FormData {
    quantity?: number;
    unit_price?: number;
    amount?: number;
    expected_date?: string;
    product?: any;
}

export default function ({ crudExpose }: { crudExpose: CrudExpose }): CreateCrudOptionsRet {
    const pageRequest = async (query: any) => {
        return await api.GetList(query);
    };
    const editRequest = async ({ form, row }: EditReq) => {
        if (row.id) {
            form.id = row.id;
        }
        return await api.UpdateObj(form);
    };
    const delRequest = async ({ row }: DelReq) => {
        return await api.DelObj(row.id);
    };
    const addRequest = async ({ form }: AddReq) => {
        return await api.AddObj(form);
    };

    const exportRequest = async (query: UserPageQuery) => {
        return await api.exportData(query);
    };

    // 采购计划字典
    const planDict = dict({
        url: '/api/purchase/plan/?status=1',  // 只获取已审批的采购计划
        value: 'id',
        label: 'title',
        cache: true,
        immediate: true
    });

    // 供应商产品字典
    const productDict = dict({
        url: '/api/supplier_product/?is_active=True',  // 只获取有效的产品，注意使用 Python 格式的 True
        value: 'id',
        label: 'product_name',
        cache: false,  // 不使用缓存，确保每次获取最新数据
        immediate: true, // 立即加载字典数据
    });

    // 获取当前日期，格式化为 YYYY-MM-DD
    const today = dayjs().format('YYYY-MM-DD');

    return {
        crudOptions: {
            request: {
                pageRequest,
                addRequest,
                editRequest,
                delRequest,
            },
            actionbar: {
                buttons: {
                    export: {
                        show: auth('PurchaseDetail:Export'),
                        text: "导出",
                        title: "导出",
                        click() {
                            return exportRequest(crudExpose.getSearchFormData());
                        }
                    },
                    add: {
                        show: auth('PurchaseDetail:Create'),
                    },
                }
            },
            rowHandle: {
                fixed: 'right',
                width: 200,
                buttons: {
                    view: {
                        link: true,
                        text: '查看',
                        order: 1,
                        show: auth('PurchaseDetail:Retrieve')
                    },
                    edit: {
                        link: true,
                        text: '编辑',
                        order: 2,
                        show: auth('PurchaseDetail:Update')
                    },
                    remove: {
                        link: true,
                        text: '删除',
                        order: 3,
                        show: auth('PurchaseDetail:Delete')
                    },
                },
            },
            columns: {
                plan: {
                    title: '采购计划',
                    type: 'dict-select',
                    search: { show: true },
                    dict: planDict,
                    column: {
                        width: 180,
                    },
                    form: {
                        rules: [{ required: true, message: '采购计划必选' }],
                        component: {
                            placeholder: '请选择采购计划',
                        },
                    },
                },
                product: {
                    title: '商品',
                    type: 'dict-select',
                    search: { show: true },
                    dict: productDict,
                    column: {
                        show: false, // 在列表中隐藏此字段
                    },
                    form: {
                        rules: [{ required: true, message: '商品必选' }],
                        component: {
                            placeholder: '请选择供应商商品',
                            filterable: true,
                            clearable: true,
                        },
                        valueChange({ form, value, immediate }) {
                            if (!value) return;
                            
                            // 使用API直接获取产品详情
                            api.getProductDetail(value).then((res: any) => {
                                if (res && res.data) {
                                    const productData = res.data;
                                    // 自动填充单价和其他相关信息
                                    form.unit_price = productData.price || 0;
                                    form.product_name = productData.product_name || '';
                                    form.product_code = productData.product_code || '';
                                    form.specification = productData.specification || '';
                                    form.unit = productData.unit || '';
                                    
                                    // 如果数量已填写，重新计算金额
                                    if (form.quantity) {
                                        form.amount = Number((form.quantity * (form.unit_price || 0)).toFixed(2));
                                    }
                                    
                                    console.log('已加载产品数据:', productData);
                                }
                            }).catch((err: any) => {
                                console.error('获取产品详情失败:', err);
                            });
                        }
                    },
                    viewForm: {
                        component: {
                            name: 'fs-dict-select',
                            readonly: true
                        }
                    },
                },
                product_name: {
                    title: '商品名称',
                    type: 'input',
                    search: { show: false },
                    column: {
                        minWidth: 160,
                        sortable: 'custom',
                    },
                    form: {
                        show: false, // 隐藏此字段，由product自动填充
                    },
                },
                specification: {
                    title: '规格型号',
                    type: 'input',
                    search: { show: false },
                    column: {
                        minWidth: 120,
                    },
                    form: {
                        show: false, // 隐藏此字段，由product自动填充
                    },
                },
                unit: {
                    title: '单位',
                    type: 'input',
                    search: { show: false },
                    column: {
                        width: 80,
                    },
                    form: {
                        show: false, // 隐藏此字段，由product自动填充
                    },
                },
                quantity: {
                    title: '数量',
                    type: 'number',
                    search: { show: false },
                    column: {
                        width: 100,
                        sortable: 'custom',
                    },
                    form: {
                        rules: [{ required: true, message: '数量必填' }],
                        component: {
                            placeholder: '请输入数量',
                            min: 1,
                        },
                    },
                },
                unit_price: {
                    title: '单价',
                    type: 'number',
                    search: { show: false },
                    column: {
                        width: 120,
                        sortable: 'custom',
                        formatter: ({ value }) => {
                            if (value === null || value === undefined || value === '') {
                                return '';
                            }
                            try {
                                const numValue = parseFloat(value);
                                return !isNaN(numValue) ? `¥${numValue.toFixed(2)}` : '';
                            } catch (e) {
                                console.error('Price formatting error:', e);
                                return value;
                            }
                        }
                    },
                    form: {
                        rules: [{ required: true, message: '单价必填' }],
                        component: {
                            placeholder: '请输入单价',
                            precision: 2,
                            step: 0.01,
                            min: 0,
                        },
                    },
                },
                amount: {
                    title: '金额',
                    type: 'number',
                    search: { show: false },
                    column: {
                        width: 120,
                        sortable: 'custom',
                        formatter: ({ value }) => {
                            if (value === null || value === undefined || value === '') {
                                return '';
                            }
                            try {
                                const numValue = parseFloat(value);
                                return !isNaN(numValue) ? `¥${numValue.toFixed(2)}` : '';
                            } catch (e) {
                                console.error('Amount formatting error:', e);
                                return value;
                            }
                        }
                    },
                    form: {
                        component: {
                            disabled: true,  // 禁用输入，由系统自动计算
                            placeholder: '系统自动计算',
                            precision: 2,
                        },
                        valueChange: ({ form, value, immediate }) => {
                            // 这里不需要处理，金额由数量和单价变化时计算
                        }
                    },
                },
                expected_date: {
                    title: '预计到货日期',
                    type: 'date',
                    search: { show: true },
                    column: {
                        width: 120,
                        component: { name: "fs-date-format", format: "YYYY-MM-DD" }
                    },
                    form: {
                        rules: [
                            { required: true, message: '预计到货日期必填' },
                            {
                                validator: (rule: any, value: string) => {
                                    if (!value) return Promise.resolve();
                                    if (dayjs(value).isBefore(dayjs(), 'day')) {
                                        return Promise.reject('预计到货日期不能早于当前日期');
                                    }
                                    return Promise.resolve();
                                }
                            }
                        ],
                        component: {
                            format: "YYYY-MM-DD",
                            valueFormat: "YYYY-MM-DD",
                            placeholder: '请选择预计到货日期',
                            disabledDate: (time: Date) => {
                                return dayjs(time).isBefore(dayjs(), 'day');
                            }
                        },
                    },
                },
            },
            form: {
                wrapper: {
                    is: "el-dialog",
                    width: "600px"
                },
                async valueChange({ key, value, form, immediate }: { 
                    key: string; 
                    value: any; 
                    form: FormData; 
                    immediate: boolean 
                }) {
                    // 当数量或单价变化时，自动计算金额
                    if (key === 'quantity' || key === 'unit_price') {
                        const quantity = form.quantity || 0;
                        const unitPrice = form.unit_price || 0;
                        form.amount = Number((quantity * unitPrice).toFixed(2));
                    }
                },
                beforeSubmit({ form }: { form: FormData }) {
                    // 提交前再次计算金额，确保数据准确
                    const quantity = form.quantity || 0;
                    const unitPrice = form.unit_price || 0;
                    form.amount = Number((quantity * unitPrice).toFixed(2));
                    return true;
                }
            },
        },
    };
} 